import 'dart:async';
import 'dart:io';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/expert/viewpoint_logic.dart';
import 'package:sports_new/entity/expert/match_play_entity.dart';
import 'package:sports_new/entity/expert/plan_Info_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/user_api.dart';
import 'package:sports_new/utils/app_config.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/expert/viewpoint/match_play_view.dart';
import 'package:sports_new/view/expert/items/plan_item.dart';
import 'package:sports_new/view/expert/viewpoint/time_countdown_view.dart';
import 'package:sports_new/view/pick/subs/subs_bar.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/html/qkd_html.dart';
import 'package:sports_new/widgets/share/share_button.dart';
import 'package:sports_new/widgets/share/share_image.dart';
import 'package:sports_new/widgets/tip_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/base/qkd_dialog.dart';

class ViewpointPage extends StatefulWidget {
  const ViewpointPage({super.key});

  @override
  State<ViewpointPage> createState() => _ViewpointPageState();
}

class _ViewpointPageState extends State<ViewpointPage> {
  final ViewpointLogic logic =
      Get.put(ViewpointLogic(), tag: "${Get.arguments}");

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ViewpointLogic>(
        tag: "${Get.arguments}",
        builder: (logic) {
          return GestureDetector(
            onHorizontalDragUpdate: (details) async {
              if (Platform.isIOS) {
                int sensitivity = 30;
                if (details.delta.dx > sensitivity) {
                  bool b = await focusRequest();
                  if (b) Get.back();
                }
              }
            },
            child: WillPopScope(
              onWillPop: () async {
                return focusRequest();
              },
              child: Scaffold(
                backgroundColor: Colours.greyF2F3F7,
                appBar: Styles.appBar(
                  onTapLeading: () async {
                    var result = await focusRequest();
                    if (result == true) Get.back();
                  },
                  titleSpacing: 0,
                  title: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 400),
                      child: logic.barShow
                          ? logic.expertView.expertBar()
                          : const QkdText("方案详情")),
                  centerTitle: true,
                  actions: [
                    ShareButton(
                        route: 'tg/expert?id=${logic.planId}',
                        color: Colors.black,
                        title: '来看看专家对这场比赛的分析',
                        logoUrl: logic.planInfo?.expertLogo,
                        onTap: () =>
                            Utils.onEvent('plan_detail_share', params: {
                              "plan_id": logic.planInfo?.planId ?? 0,
                              'param2': logic.roomId == null ? '0' : '1'
                            }),
                        needChannel: true,
                        imageWidget: <Widget>() => ShareImage.viewpoint(
                                param: 'tg/expert?id=${logic.planId}',
                                widgets: [
                                  _header(),
                                  if (logic.planInfo?.matchBries.hasValue ==
                                      true)
                                    _matchPlay(isShare: true),
                                  _content(isShare: true),
                                ])).paddingOnly(right: 16),
                  ],
                ),
                body: VisibilityDetector(
                  key: const Key("expert viewpoint detail"),
                  onVisibilityChanged: (info) {
                    if (info.visibleBounds.isEmpty) {
                      return;
                    }
                    logic.doRequestData();
                  },
                  child: SafeArea(
                    top: false,
                    bottom: false,
                    child: LoadingWidget<bool>(
                      isLoading: logic.planInfo == null,
                      data: !(logic.planInfo?.planId.hasValue ?? false),
                      child: () => EasyRefresh(
                        controller: logic.refreshController,
                        scrollController: logic.refreshScroll,
                        onRefresh: () async {
                          await logic.doRequestData();
                          logic.refreshController.finishRefresh();
                        },
                        child: Stack(
                          children: [
                            ListView(
                              controller: logic.refreshScroll,
                              children: [
                                _header(),
                                if (logic.planInfo?.matchBries.hasValue == true)
                                  _matchPlay(),
                                _content(),
                                if (!logic.readable)
                                  Block(
                                      cardStyle: const CardStyle(
                                        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      ),
                                      child: Container(
                                        height: 52,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 12),
                                        alignment: Alignment.center,
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            const QkdText("自动关注比赛",
                                                fontSize: 16),
                                            CupertinoSwitch(
                                              value: logic.focusMatch,
                                              onChanged: (open) =>
                                                  logic.focusMatch = open,
                                              activeColor: Colours.main,
                                              thumbColor: Colours.white,
                                            )
                                          ],
                                        ),
                                      )),
                                if (logic.planInfo?.pushPlan != null &&
                                    logic.readable &&
                                    AppConfig.config.showRelative &&
                                    ModeConfig.expert)
                                  _otherViewPoints(),
                                const SizedBox(height: 16),
                                tip(),
                                Container(height: logic.isCanPay ? 80 : 95)
                              ],
                            ),
                            if (logic.planInfo?.showFooter ?? false)
                              Positioned(
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                  child: _buyBottom())
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }

  Widget _header() {
    final pv = logic.planInfo?.pv ?? 0;
    String pvStr = "$pv人感兴趣";
    if (pv > 10000) {
      pvStr = "${pv ~/ 10000}W+人感兴趣";
    }
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.all(12)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            QkdText(
              logic.planInfo?.planTitle ?? "",
              textAlign: TextAlign.left,
              fontSize: 22,
              fontWeight: FontWeight.w500,
            ),
            const SizedBox(height: 10),
            DefaultTextStyle(
                style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xff999999),
                    fontWeight: FontWeight.w400),
                child: Row(
                  children: [
                    QkdText((logic.planInfo?.pubTime
                                ?.formatedString("yyyy-MM-dd HH:mm") ??
                            "") +
                        " 发布"),
                    const Spacer(),
                    QkdText(pvStr),
                  ],
                )),
            Container(height: 8),
            const Divider(color: Colours.greyEE, height: 0.5),
            Container(height: 11),
            logic.expertView.expertRow()
          ],
        ));
  }

  Widget _matchPlay({bool isShare = false}) {
    return Block(
        cardStyle: const CardStyle(
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
        ),
        child: Column(children: [
          ...logic.planInfo?.matchBries
                  ?.map<Widget>((e) => MatchPlayView(
                          matchPlay:
                              MatchPlayEntity.fromViewpoint(logic.planInfo),
                          match: e,
                          roomId: logic.roomId,
                          readable: isShare
                              ? (logic.planInfo?.planStatus != 0 ||
                                  logic.planInfo?.priceReal == "0.00")
                              : logic.readable)
                      .paddingSymmetric(horizontal: 12))
                  .toList()
                  .insertEvery(const Divider(color: Colours.greyEE, height: 0.5)
                      .paddingSymmetric(horizontal: 12)) ??
              [],
          if (logic.planInfo?.activityId != null)
            Container(
              height: 29,
              color: Colours.main.withOpacity(0.05),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(width: 12),
                  if (logic.planInfo?.activityId == 1 ||
                      logic.planInfo?.activityId == 2)
                    QkdText(
                      "该方案享受${logic.planInfo?.activityId == 1 ? "首购不中退款" : "粉丝不中退款"}",
                      color: Colours.main,
                      fontSize: 12,
                      needCenter: true,
                    ),
                  if (logic.planInfo?.activityId == 3)
                    const QkdText(
                      "该方案享受“会员免费看”权益",
                      color: Colours.main,
                      fontSize: 12,
                      needCenter: true,
                    ),
                  Container(width: 4),
                  Image.asset(
                    width: 12,
                    height: 12,
                    Utils.getImgPath("icon_wenhao.png"),
                  )
                ],
              ).tap(() {
                if (logic.planInfo?.activityId == 1 ||
                    logic.planInfo?.activityId == 2) {
                  Get.dialog(QkdDialog.singleBUTTON(
                      "${logic.planInfo?.activityId == 1 ? "首购" : "粉丝"}不中退说明",
                      content: [
                        if (logic.planInfo?.activityId == 1)
                          "1.首次购买该专家的方案且选项不中，即可享受不中退活动。",
                        if (logic.planInfo?.activityId == 2)
                          "1. 购买方案前关注专家，即可享受不中退活动。",
                        "2. 建议选项中的首选和次选均不中，则为不中。",
                        "3. 比赛赛果确认后的半小时内，实付球币金额自动退款至球币余额内。"
                      ].join("\n"),
                      confirmText: "知道了"));
                }
                if (logic.planInfo?.activityId == 3) {
                  Get.dialog(const QkdDialog.singleBUTTON("会员免费解锁方案",
                      content: "会员每天可免费解锁1篇专家方案", confirmText: "知道了"));
                }
              }),
            ),
        ]));
  }

  Widget _content({bool isShare = false}) {
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.symmetric(horizontal: 4, vertical: 12)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const QkdText("专家分析", fontSize: 16, fontWeight: FontWeight.w500)
                .paddingSymmetric(horizontal: 8),
            if (logic.planInfo?.planSummary != null ||
                logic.planInfo?.isVideo == 1)
              QkdHtml(
                id: logic.planId ?? 0,
                player: logic.videoLogic,
                margin: Margins.only(top: 12, left: 8, right: 8),
                data: """
            ${logic.planInfo?.isVideo == 1 && logic.readable ? """<p><video playsinline style="width: 100%;" controls="controls"><source src=${logic.planInfo?.videoUrl} type="video/mp4" /></video></p>""" : ""}
            ${logic.planInfo?.planSummary ?? ""}
            ${logic.planInfo?.priceReal != "0.00" && !logic.readable ? "<feeline>${logic.planInfo?.isVideo == 1 ? "视频" : "文字"}</feeline>" : ""}
            ${isShare ? (logic.planInfo?.planStatus != 0 || logic.planInfo?.priceReal == "0.00") : logic.readable ? logic.planInfo?.feeContent ?? "" : ""}
            """,
                showFeeLine: logic.planInfo?.planSummary?.isNotEmpty == true,
              ),
            if (isShare
                ? (logic.planInfo?.planStatus != 0 ||
                    logic.planInfo?.priceReal == "0.00")
                : logic.readable) ...[
              if (!isShare)
                GestureDetector(
                  onTap: () => Get.toNamed(Routes.viewReportChoice,
                      arguments:
                          "方案ID：${logic.planId}\n专家名称：${logic.planInfo?.expertName}"),
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                    child: Row(
                      children: [
                        Image.asset(Utils.getImgPath("report_plan.png"),
                            width: 15),
                        Container(width: 1),
                        const QkdText("举报观点",
                            fontSize: 12, color: Colours.grey99)
                      ],
                    ),
                  ),
                )
            ] else ...[
              TimeCountdownView(logic.planInfo!.saleEndTime ?? '',
                      isShare: isShare, isVideo: logic.planInfo?.isVideo == 1)
                  .paddingSymmetric(horizontal: 4),
              if (!isShare)
                Padding(
                  padding: const EdgeInsets.fromLTRB(4, 8, 4, 0),
                  child: SubsBar(
                    expertId: logic.planInfo?.expertId ?? "",
                  ),
                ),
            ],
          ],
        ));
  }

  Widget tip() {
    return const Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        QkdText("友情提示", fontSize: 12, color: Colours.grey66),
        TipWidget(type: "viewpoint_tip"),
      ],
    ).paddingSymmetric(horizontal: 16);
  }

  Widget _otherViewPoints() {
    return Block(
      cardStyle: const CardStyle(
          padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const QkdText(
                '该专家的其他方案',
                textAlign: TextAlign.left,
                fontSize: 16,
                height: 1.1,
                color: Colours.text,
                fontWeight: FontWeight.w600,
              ),
              const SizedBox(width: 5),
              QkdText("(${logic.planInfo!.pushPlan!.length})",
                  fontSize: 12, height: 1.1, color: Colours.grey66)
            ],
          ),
          Container(height: 8),
          ...logic.planInfo?.pushPlan
                  ?.map<Widget>(
                      (e) => PlanItem(entity: e, isExpertDetailView: true))
                  .toList()
                  .insertEvery(
                      const Divider(height: 0.5, color: Colours.greyEE)) ??
              [],
        ],
      ),
    );
  }

  Widget _buyBottom() {
    final coupon =
        logic.coupons?.filterOrNull((item) => item.autoSelect == 1)?.first;
    final price = (double.tryParse(logic.planInfo?.priceReal ?? "") ?? 0) -
        (coupon?.gold ?? 0);
    final nprice =
        coupon == null ? logic.planInfo?.priceReal : price.toStringAsFixed(2);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (logic.planInfo?.footerContent?.isNotEmpty ?? false)
          Container(
            height: 28,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            margin: const EdgeInsets.only(left: 12, right: 12, bottom: 8),
            alignment: Alignment.center,
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
                color: Colours.white,
                borderRadius: BorderRadius.circular(24),
                boxShadow: [
                  BoxShadow(
                      color: const Color(0xFF87909D).withOpacity(0.13),
                      blurRadius: 12,
                      offset: const Offset(0, 4))
                ]),
            child: Row(
              children: [
                Image.asset(width: 15, Utils.getImgPath("planinfo_alert.png")),
                const SizedBox(width: 5),
                QkdText(logic.planInfo?.footerContent ?? "方案所含比赛已开始，当前不可付费阅读！",
                    fontSize: 12,
                    color: !logic.isCanPay ? Colours.main : Colours.grey99)
              ],
            ),
          ),
        Padding(
          padding: EdgeInsets.fromLTRB(
              12, 0, 12, 24 + MediaQuery.of(context).padding.bottom),
          child: Stack(
            children: [
              Container(
                height: 48,
                alignment: Alignment.center,
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                    color: Colours.white,
                    borderRadius: BorderRadius.circular(24),
                    boxShadow: [
                      BoxShadow(
                          color: const Color(0x529BA9BE).withOpacity(0.32),
                          blurRadius: 12,
                          offset: const Offset(0, 4))
                    ]),
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.only(left: 16, right: 4),
                      height: 48,
                      child: Row(
                        children: [
                          // Image.asset(Utils.getImgPath("gold_icon_yellow.png"),width: 16),
                          // Container(width: 3),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              coupon != null
                                  ? QkdText(
                                      "${price.toStringAsFixed(2)}球币"
                                          .changeUnit,
                                      color: Colours.main,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      height: 1.4)
                                  : QkdText(
                                      "${logic.planInfo?.priceReal ?? "0"}球币"
                                          .changeUnit,
                                      color: Colours.main,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      height: 1.4),
                              if (nprice != logic.planInfo?.price)
                                QkdText(
                                  "${logic.planInfo?.price ?? "0"}球币"
                                      .changeUnit,
                                  decoration: TextDecoration.lineThrough,
                                  fontSize: 12,
                                  color: Colours.grey99,
                                  height: 1.4,
                                ),
                            ],
                          ),
                          const Spacer(),
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 4),
                            child: Container(
                              height: 40,
                              clipBehavior: Clip.antiAlias,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(20)),
                              child: Row(
                                children: [
                                  if (logic.planInfo?.activityId == 3 &&
                                      logic.isCanPay)
                                    Container(
                                            height: 40,
                                            alignment: Alignment.center,
                                            padding: const EdgeInsets.only(
                                                right: 12, left: 16),
                                            decoration: const BoxDecoration(
                                                gradient: LinearGradient(
                                                    colors: [
                                                  Color(0xFFFFE7C1),
                                                  Color(0xFFF1CD8E)
                                                ])),
                                            child: QkdText(
                                                logic.planInfo?.vipContent ??
                                                    '',
                                                fontWeight: FontWeight.w500,
                                                color: Colours.brown6A3313))
                                        .tap(logic.doVipPay),
                                  Container(
                                      height: 40,
                                      width: logic.planInfo?.activityId == 3 &&
                                              logic.isCanPay
                                          ? null
                                          : 108,
                                      alignment: Alignment.center,
                                      padding: const EdgeInsets.only(
                                          left: 12, right: 16),
                                      color: !logic.isCanPay
                                          ? Colours.greyF2
                                          : Colours.main,
                                      child: QkdText(
                                        "支付阅读",
                                        color: !logic.isCanPay
                                            ? Colours.greyCC
                                            : Colors.white,
                                        fontWeight: FontWeight.w500,
                                      )).tap(logic.clickToPay)
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              if (logic.planInfo?.activityId == 1 ||
                  logic.planInfo?.activityId == 2)
                Positioned(
                    top: 0,
                    right: 0,
                    child: Image.asset(
                      Utils.getImgPath(logic.planInfo?.activityId == 1
                          ? "buzhongtui_first.png"
                          : "buzhongtui_fans.png"),
                      width: 54,
                      height: 14,
                    ))
            ],
          ),
        ),
      ],
    );
  }

  static final focusTipedMap = {};

  Future<bool> focusRequest() async {
    if (focusTipedMap[logic.planInfo?.planId] ?? false) {
      return true;
    }
    if (logic.planInfo?.isFocus == 0 &&
        logic.readable &&
        logic.planInfo?.planStatus == 0) {
      focusTipedMap[logic.planInfo?.planId] = true;
      var result = await Get.dialog(askFocus());
      return result;
    } else {
      return true;
    }
  }

  Widget askFocus() {
    return Dialog(
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: SizedBox(
        width: 280,
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 33),
              child: const QkdText(
                "如果您认为专家的方案写的还不错可以关注一下哟！",
                textAlign: TextAlign.center,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              )),
          Container(
            width: double.infinity,
            height: 0.5,
            color: Colours.greyEE,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Flexible(
                fit: FlexFit.tight,
                child: QkdButton(
                    onPressed: () => Get.back(result: true),
                    text: "以后再说",
                    height: 44,
                    textStyle: const TextStyle(fontWeight: FontWeight.w500),
                    foregroundColor: Colours.grey66),
              ),
              Container(
                width: 0.5,
                height: 44,
                color: Colours.greyEE,
              ),
              Flexible(
                fit: FlexFit.tight,
                child: QkdButton(
                    onPressed: () async {
                      UserApi.focus(expertId: logic.planInfo?.expertId ?? "");
                      Get.back(result: true);
                    },
                    text: "关注",
                    height: 44,
                    textStyle: const TextStyle(fontWeight: FontWeight.w500),
                    foregroundColor: Colours.main),
              ),
            ],
          )
        ]),
      ),
    );
  }
}
